<!--这是店铺装修-友商链接组件-->
<template>
  <div class="app-container">
    <el-form v-loading="formLoading" :model="postForm" :rules="rules" ref="postForm" label-width="220px" label-position="right">
      <el-form-item label="排序号：" prop="sort">
        <el-input type="number" v-model.number="postForm.sort" placeholder="请输入排序号" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="链接：" prop="link">
        <el-input v-model="postForm.link" placeholder="请输入图片链接" style="width: 650px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="图片(宽750*高325)：" prop="url">
        <el-upload
          ref="avatarUpload"
          name="avatar"
          :action="imageUploadUrl"
          list-type="picture"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :on-remove="handleAvatarRemove"
          :on-exceed="handleAvatarExceed"
          :file-list="avatarList"
          :limit="1"
          :auto-upload="false"
          style="width: 650px">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitAvatarUpload">上传到服务器</el-button>
        </el-upload>
      </el-form-item> -->
      <el-form-item label="图片(宽200*高100)：" prop="url">
        <image-component class="fl" :image="postForm.url" :width="'200px'" :height="'100px'"></image-component>
        <el-button  class="fl el-btn" type="primary" icon="upload" style="bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">
          更换图片
        </el-button>
        <image-cropper :width="200" :height="100" :url="imageUploadUrl" @close='closeImageCropper'
                      @crop-upload-success="cropSuccess" langType="zh"
                      :key="imagecropperKey" v-show="imagecropperShow"></image-cropper>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-loading="btnLoading" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getImage, addImage, updateImage } from '@/api/systemManage'
import imageComponent from '@/components/imageComponent'
import ImageCropper from '@/components/ImageCropper'
const postForm = {
  sort: null, // 排序号
  link: null, // 图片链接
  url: ' ',
  type: 2
}

const validateNumber = (rule, value, callback) => {
  if (value && isNaN(value)) {
    callback('请输入正确的数值')
  } else {
    if (value < 0 || value == null || value == '') {
      callback('请输入正确的数值')
    }
    callback()
  }
}

const rules = {
  sort: [{ required: true, trigger: 'blur', validator: validateNumber }],
  url: [{ required: true, message: '请上传图片', trigger: 'submitForm' }]
  // link: [{ required: true, message: '请输入图片链接地址', trigger: 'submitForm' }]
}

export default {
  components: {
    imageComponent,
    ImageCropper
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, postForm),
      rules,
      imageUploadUrl: process.env.BASE_API + '/common/companies/imageUpload',
      formLoading: false,
      btnLoading: false,
      avatarList: [],
      imagecropperShow: false,
      imagecropperKey: 0
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      if (this.isEdit) {
        const imageId = this.$route.params.id
        getImage(imageId).then(res => {
          if (res.data.statusCode == 200) {
            this.postForm = res.data.data
            if (this.postForm.url) {
              this.avatarList = [{ url: this.postForm.url }]
            }
          } else {
            this.$message({
              message: '数据获取失败，请稍后再试！',
              type: 'warning'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // submitAvatarUpload() {
    //   this.$refs.avatarUpload.submit()
    // },
    // handleAvatarSuccess(response, file, fileList) {
    //   if (response.statusCode == 200) {
    //     this.postForm.url = response.data.imageUrl
    //     this.$message({
    //       message: '上传成功!',
    //       type: 'info'
    //     })
    //   } else {
    //     this.$message({
    //       message: '上传失败，请稍候再试!',
    //       type: 'info'
    //     })
    //   }
    // },
    // handleAvatarRemove(file, fileList) {
    //   this.postForm.url = null
    // },
    // handleBeforeUpload(file) {
    //   const isImg = file.type == 'image/jpeg' || file.type == 'image/png'
    //   const isLt3M = file.size / 1024 / 1024 < 3
    //   if (!isImg) {
    //     this.$message.warning('上传图片只能是 JPG 或 PNG 格式')
    //   }
    //   if (!isLt3M) {
    //     this.$message.warning('上传图片大小不能超过 3MB')
    //   }
    //   return isImg && isLt3M
    // },
    // handleAvatarExceed(files, fileList) {
    //   this.$message.warning('请先删除已有图片再上传')
    // },
    handleCreate() {
      addImage(this.postForm).then(res => {
        if (res.data.statusCode == 200) {
          this.$notify({
            title: '提示',
            message: '提交成功!',
            type: 'success'
          })
          this.btnLoading = false
          this.formLoading = false
          this.close()
        } else {
          this.btnLoading = false
          this.formLoading = false
          this.$notify({
            title: '提示',
            message: '提交失败!',
            type: 'error'
          })
        }
      }).catch(err => {
        this.btnLoading = false
        this.formLoading = false
        console.log(err)
      })
    },
    // 图片裁剪
    closeImageCropper() {
      this.imagecropperShow = false
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.postForm.url = resData.data.imageUrl
    },
    handleUpdate() {
      const imageId = this.$route.params.id
      updateImage(imageId, this.postForm).then(res => {
        if (res.data.statusCode == 200) {
          this.$notify({
            title: '提示',
            message: '提交成功!',
            type: 'success'
          })
          this.btnLoading = false
          this.formLoading = false
          this.close()
        } else {
          this.btnLoading = false
          this.formLoading = false
          this.$notify({
            title: '提示',
            message: '提交失败!',
            type: 'error'
          })
        }
      }).catch(err => {
        this.btnLoading = false
        this.formLoading = false
        console.log(err)
      })
    },
    close() {
      this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
        const latestView = views.slice(-1)[0]
        if (latestView) {
          const activeName = localStorage.getItem('manageBar')
          this.$router.push({ name: 'manage', params: { activeName: activeName }}) // latestView.path
        } else {
          this.$router.push('/')
        }
      })
    },
    submitForm() {
      if (this.postForm.url == null) {
        this.$message.warning('请上传图片')
        return
      }

      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.btnLoading) {
            return
          }
          this.btnLoading = true
          this.formLoading = true
          if (this.isEdit) {
            this.handleUpdate()
          } else {
            this.handleCreate()
          }
        } else {
          console.log('error submit!')
          return false
        }
      })
    }
  }
}
</script>
<style scoped>

</style>
